<template>
  <div class="BgHandle">
    <div class="container">
      <loading :isLoading="isLoading" :text="'渲染中...'">
        <div class="canvasBox">
          <canvas id="copyCan" ref="copyCan" style="display:none;"></canvas>
          <canvas id="cropCan" ref="cropCan"></canvas>
        </div>
      </loading>
    </div>
    <div class="operation">
      <div class="footer">
        <div 
          class="buttonInfo"
          v-show="infoShow"
          @click="test"
          ref="buttonInfo"
        >
          <div class="footer-flood">
              <van-slider 
              :disabled="isLoading"
              v-model="temp.tempRange" 
              range
              :active-color="temp.color"
              @change="changeSlider(selectId)" 
              class="slider"
            />
            <div class="select-slider">
              <!-- <div class="select-slider-left">
                <span>{{ Math.round(this.temp.tempRange[0] / 100 * 255) + ' , '}}</span>
                <span>{{ Math.round(this.temp.tempRange[1] / 100 * 255) }}</span>
              </div> -->
              <!-- RGB -->
              <span 
               class="select-style"
               :class="{active : selectId === 0}"
               style="background-color:#ccc"
                @click="selectClick(0)" 
              >
              </span>
              <span class="select-hr"></span>
              <span 
                class="select-style"
                v-for="item in selectSlider"
                :key="item.id"
                :style="`background-color:${item.color}`"
                :class="{
                  active : item.id === selectId
                }"
                @click="selectClick(item.id)"
              ></span>
            </div>
          </div>
          
        </div>
        <div class="buttonList" style="padding:0 20px">
          <router-link :to="{name: 'Crop'}" class="footer-btn"> 
            <i class="iconfont icon-btn">&#xe681;</i>
            <span>上一步</span>
          </router-link>
          <div class="toolArea" @click="popupChange">
            <span>背景调整</span>
          </div>
          <span @click="toMoreTool" class="footer-btn">
            <span>下一步</span>
            <i class="iconfont icon-btn">&#xe683;</i>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import cutoutFlood from '../util/flood-fill'
import gaussBlur from '../util/gauss-blur'
import Loading from '../components/loadingBox'

export default {
  components : {
    Loading
  },
  data() {
    return {
      isPopup: true,
      isLoading: false,
      range : [   // 阈值调整区间
        [0.36, 0.3, 0.40],
        [0.3, 0.2, 0.3]
      ],
      rangeSlider : {
        R : [],
        G : [],
        B : [],
      },
      temp :{
        tempRange : [],
        color : '#999'
      } ,  // 中间件
      selectId : 0,
      selectSlider :[
        {
          id : 1,
          type : 'R',
          color : '#F5222D',
        },
        {
          id : 2,
          type : 'G',
          color : '#52c41a',
        },
        {
          id : 3,
          type : 'B',
          color : '#2D9CD4',
        }
      ],
      canvasWidth : '',  // 画布宽度
      canvasHeight : '',  // 画布高度
      ctx : '',  // 展示画布
      copyCtx : '',  // 复制的画布
      linePoint : [],  // 边缘点
      lineWidth : 0.1,  
      sigma : 1,
      radius : 1,
      targetColor : [0,0,0,255],
      afterFloodData : [],   // 背景去除后的data
      infoShow : true,
    }
  },
  methods : {
    test(){
      console.log('-------------------------------------------------------');
    },
    flood(){
      // let canvas = this.$refs.cropCan;
      // let data = cutoutFlood(canvas,this.range)
      console.log('?????????');
    },
    // 通过裁剪数据初始化copy画布和展示画布
    initCanvas(){
      let canvas = this.$refs.cropCan;
      let copy = this.$refs.copyCan;
      this.canvasWidth = this.cropData.width;
      this.canvasHeight = this.cropData.height;
      copy.width = this.canvasWidth
      copy.height = this.canvasHeight
      canvas.width = this.canvasWidth
      canvas.height = this.canvasHeight
      this.ctx = canvas.getContext('2d');  // 初始化画布
      this.copyCtx = copy.getContext('2d');
      this.copyCtx.putImageData(this.cropData.data,0,0);
      this.ctx.putImageData(this.cropData.data,0,0);
      return { canvas, copy }
    },
    // 获取画布数据
    getCtxData(ctx) {
      return ctx.getImageData(0,0,this.canvasWidth,this.canvasHeight)
    },
    // 边缘模糊
    edgeBlur(){
      let cloneData = this.copyImageData(this.afterFloodData);
      this.ctx.putImageData(cloneData, 0, 0);
      // 处理得到模糊数据
      let blurData = gaussBlur(cloneData, this.linePoint, this.radius, this.lineWidth, this.sigma);
      this.ctx.putImageData(blurData, 0, 0);
    },
    copyImageData(imagedata){
        return new ImageData(new Uint8ClampedArray(imagedata.data),imagedata.width,imagedata.height);
    },
    // 初始化range
    initRange(color){
      let R = color[0],
          G = color[1],
          B = color[2]
      this.rangeSlider.R = [min(this.range[0][0],R),max(this.range[1][0],R)];
      this.rangeSlider.G = [min(this.range[0][1],G),max(this.range[1][1],G)];
      this.rangeSlider.B = [min(this.range[0][2],B),max(this.range[1][2],B)];

      function min(range,color){
        let min = parseInt( ( (1 - range) * color) / 255 * 100 );
        return min < 0 ? 0 : min;
      }
      function max(range,color){
        let max = parseInt( ( (1 + range) * color) / 255 * 100 );
        return max > 100 ? 100 : max;
      }
    },
    // 选择
    selectClick(id){
      this.selectId = id;
      if(id == 0){
        let min = parseInt((this.rangeSlider['R'][0] +  this.rangeSlider['G'][0] + this.rangeSlider['B'][0]) / 3);
        let max = parseInt((this.rangeSlider['R'][1] +  this.rangeSlider['G'][1] + this.rangeSlider['B'][1]) / 3);
        this.temp.tempRange = [min,max];
        this.temp.color = '#999';
      }else {
        let type = this.selectSlider[id - 1].type;
        console.log('rangeSlider',this.rangeSlider[type])
        this.temp.tempRange = this.rangeSlider[type];
        this.temp.color = this.selectSlider[id - 1].color;
      }
    },
    // slider参数发生改变，改变range => []
    // 通过调节slider调整range值
    changeSlider(id){
      let color = id !== 0 ? this.targetColor[id - 1] : avgColor(this.targetColor);
      let min = this.temp.tempRange[0];
      let max = this.temp.tempRange[1];
      let rangeMin = toMin(min,color);
      let rangeMax = toMax(max,color);
      console.log(color,min,max,rangeMin,rangeMax);

      this.$toast({
        message : `[ ${Math.round(this.temp.tempRange[0] / 100 * 255)} , ${Math.round(this.temp.tempRange[1] / 100 * 255)} ] \n界值 ${this.colorCritical}`,
        position : 'top'
      });

      if(id === 0){
        for(let i = 0; i < 3; i++){
          this.range[0].splice(i,1,rangeMin);
          this.range[1].splice(i,1,rangeMax);
        }
        this.initRange(this.targetColor)
      }else {
        let type = this.selectSlider[id - 1].type;
        this.range[0].splice(id - 1, 1, rangeMin);
        this.range[1].splice(id - 1, 1, rangeMax);
        this.rangeSlider[type][0] = min;
        this.rangeSlider[type][1] = max;
      }
      function toMax (data,color){
        if(color === 0) color = 1
        let max = (data / 100 * 255) / color - 1;
        return max < 0 ? 0 : max;
      }
      function toMin(data,color){
        if(color === 0) color = 1
        let min =  1 - (data / 100 * 255) / color;
        return min < 0 ? 0 : min;
      }
      function avgColor(color){
        return parseInt((color[0] + color[1] + color[2]) / 3);
      }
    },
    getMomentCanData(){
      let canvas = this.$refs.cropCan;
      let styleRes = window.getComputedStyle(canvas);
      let domWidth = parseFloat(styleRes.getPropertyValue('width'));
      let domHeight = parseFloat(styleRes.getPropertyValue('height'));
      let width = canvas.width;
      let height = canvas.height;
      console.log(domWidth,domHeight,width,height);
      let ctx = canvas.getContext('2d');
      let data = ctx.getImageData(0,0,canvas.width,canvas.height);
      console.log(data);
      this.$store.state.noBgCan = { data, width, height };
    },
    popupChange() {
      this.isPopup = !this.isPopup;
      let buttonInfoStyle = this.$refs.buttonInfo.style;
      if(this.isPopup) {
        buttonInfoStyle.bottom = '0px';
      }else {
        buttonInfoStyle.bottom = '-45px';
      }
    },
    toMoreTool(){
      this.getMomentCanData();
      this.$router.push('/MoreTool');
    }
  },
  computed : {
    // 获取裁剪后的数据
    cropData() {
      return this.$store.state.cropData;
    },
    // 返回颜色临界值 
    colorCritical() {
      if(this.selectId === 0){
        return parseInt((this.targetColor[0] + this.targetColor[1] + this.targetColor[2]) / 3)
      }
      return this.targetColor[this.selectId - 1];
    }
  },
  watch : {
    'lineWidth' :  function(){
      this.edgeBlur();
    },
    'sigma' : function(){
      this.edgeBlur();
    },
    'radius' : function() {
      this.edgeBlur();
    },
    'afterFloodData' : function() {
      console.log('afterData有变化')
    },
    'range' : {
      handler : async function(){
        this.isLoading = true;
        console.log(this.range);
        let canvas = this.$refs.cropCan;
        let copy = this.$refs.copyCan;
        let self = this;
        cutoutFlood(copy,canvas,this.range,function(data) {
          self.linePoint = data.edgeLinePoint;
          self.$store.state.linePoint = self.linePoint;
          self.afterFloodData = self.getCtxData(self.ctx);
          self.edgeBlur();
          self.isLoading = false;
        });
      },
      deep : true,
    },
  },
  mounted () {
    window.BgVm = this;
    this.isLoading = true;
    let { canvas,copy } = this.initCanvas();   // 初始化canvas
    let self = this;
    cutoutFlood(copy,canvas,this.range,function(data){
      self.targetColor = data.color;  // 获取target颜色
      self.targetColor.forEach((ele,index) => {
        console.log(self,self.range,index)
        console.log(ele)
        if(ele <= 1) {
          // self.range[0][index] = 1;
          // self.range[1][index] = 0;
          self.range[0].splice(index,1,1)
          self.range[1].splice(index,1,0)
        }
      })
      self.$store.state.targetColor = self.targetColor;
      self.initRange(self.targetColor);
      self.selectClick(0);
      self.linePoint = data.edgeLinePoint;
      self.$store.state.linePoint = self.linePoint;
      self.afterFloodData = self.getCtxData(self.ctx);
      self.edgeBlur();
      self.isLoading = false;
    });
  }
}
</script>


<style scoped>
  .BgHandle{
    display: flex;
    height: calc(100vh - 46px);
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
  }

  .container{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 101px);
    padding-top: 15px;
    padding-bottom: 60px;
  }

  .container .canvasBox {
    display: block;
    box-shadow: 0 0 20px #ccc;
    background: #fff;
    background-image: linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd), 
                            linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd);
                            background-image: -webkit-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd), 
                            -webkit-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd);
                            background-image: -moz-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd), 
                            -moz-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd);
                            background-image: -o-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd), 
                            -o-linear-gradient(45deg, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%, #ddd);
    background-size: 30px 30px;
    background-position: 0 0, 15px 15px;
  }

  .container .canvasBox canvas {
    display: block;
    min-width: 75vw;
    max-height: calc(98vh - 131px);
    max-width: 90vw;
  }
  
  /* 操作区域 */
  .operation{
    position: relative;
  }

  .operation .footer {
    position: absolute;
    left: -50vw;
    bottom: 0;
    width: 100vw;
    height: 55px;
    line-height: 55px;
    background: #fff;
    text-align: center;
  }

  .operation .footer .buttonInfo {
    position: absolute;
    z-index: 5;
    width: 100vw;
    height: auto;
    padding-bottom: 55px;
    background-color: #fff;
    bottom: 0;
    transition: all .3s;
  }

  .operation .footer .slider {
    transform: translateX(-50%);
    width: 75vw;
    left: 50%;
  }

  .operation .footer .select-slider{
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding-top: 15px;
    /* line-height: 40px; */
  }

  .operation .footer .select-hr {
    display: inline-block;
    height: 25px;
    width: 1px;
    background: #999;
    margin: 0 5px;
  }

  .operation .footer .select-style{
    display: inline-block;
    width: 25px;
    height: 25px;
    border-radius: 50%;
    margin: 0 10px;
    transition: all .2s;
  }

  .operation .footer .select-style.active{
    box-sizing: border-box;
    width: 28px;
    height: 28px;
    border: 3px solid rgba(58, 58, 58, 0.3);
  }

  .operation .footer .buttonList{
    display: flex;
    flex-direction: row;
    background: #fff;
    position: relative;
    z-index: 999;
  }

  .operation .footer .buttonList .toolArea {
    flex: 1;
    text-align: center;
  }

  .footer-btn {
    color: rgb(0, 102, 255);
    transition: all .2s;
    padding: 0 6px;
    border-radius: 10px;
  }

  .footer-btn:active {
    font-weight: 600;
    font-size: 17px;
    color: #888;
  }

  .footer-btn .icon-btn {
    font-size: 14px;
    padding: 0 5px;
  }

</style>